package cspro;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	public static void listenConnect() {
		try {
			/** 创建ServerSocket*/
			// 创建一个ServerSocket在端口2013监听客户请求
			ServerSocket serverSocket =new ServerSocket(2013);
			// 侦听并接受到此Socket的连接,请求到来则产生一个Socket对象，并继续执行
			Socket socket = serverSocket.accept();
			new Thread(new Runnable() {
				public void run() {
					receiveMsg(socket);
					sendMsg(socket);
				}
			}).start();
//			new Thread(new Runnable() {
//				public void run() {
//					sendMsg(socket);
//				}
//			}).start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 接受客户端发来的信息
	 * @param socket
	 * @return
	 * @author: cyj
	 * @date: 2017年10月9日 下午1:20:59
	 */
	public static String receiveMsg(Socket socket){
		// 输入读入一字符串
		String result = null;
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			result = bufferedReader.readLine();
			System.out.println("Server say : " + result);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	
	public static void sendMsg(Socket socket){

		PrintWriter printWriter = null;
		
		try {
			printWriter = new PrintWriter(socket.getOutputStream());
			printWriter.print("hello Client, I am Server!");
			printWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			printWriter.close();
		}

	}
}
